import store from 'store2';
import { ROOT_URL } from '@ey-utils/utils/utils';

const THEME_KEY = 'themeKey';

export interface ThemeConfigItem {
  key: string;
  name: string;
  backgroundColor: string;
}

export const THEME_CONFIG: ThemeConfigItem[] = [
  {
    key: 'themePurple',
    name: '高端紫',
    backgroundColor: '#798AD7',
  },
  {
    key: 'pocDark',
    name: '商务黑',
    backgroundColor: '#000',
  },
  {
    key: 'deepBlue',
    name: '深蓝',
    backgroundColor: '#2da8e6',
  },
];

export const setTheme = (theme: string) => {
  store.set(THEME_KEY, theme);
};

export const getTheme = (): string => {
  return store.get(THEME_KEY) || THEME_CONFIG[0].key;
};

export const isPurpleTheme = () => {
  const theme = getTheme();

  return theme === THEME_CONFIG[0].key;
};

export const changeTheme = () => {
  const body = document.querySelector('body');
  return
  if (!body) return;

  const themeId = 'theme-style-engine';

  const styleLinkSelector = `#${themeId}`;

  let styleLink = document.querySelector(styleLinkSelector) as HTMLLinkElement;

  const timestamp = window.theme_build_timestamp || '';

  const theme = getTheme();

  const href = `${ROOT_URL}/theme/${theme}${timestamp ? `.${timestamp}.` : '.'}css`;

  if (styleLink) {
    // 假如存在id为theme-style 的link标签，直接修改其href
    styleLink.href = href; // 切换 antd 组件主题
    body.className = `body-wrap-${theme}`; // 切换自定义组件的主题
  } else {
    // 不存在的话，则新建一个
    styleLink = document.createElement('link');
    styleLink.type = 'text/css';
    styleLink.rel = 'stylesheet';
    styleLink.id = themeId;

    styleLink.href = href; // 切换 antd 组件主题
    body.className = `body-wrap-${theme}`; // 切换自定义组件的主题

    document.body.append(styleLink);
  }
};
